package com.seestech.sell.common.config.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description  blob  转 String  in   mybatis
 * Created by idiot on 2017/3/7.
 */
public class MyBlobTypeHandler extends BaseTypeHandler<String> {
    private static Logger logger = LoggerFactory.getLogger(MyBlobTypeHandler.class);
    //###指定字符集
    private static final String UTF8_charset = "UTF-8";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        byte[] bytes;
        try {
            //###把String转化成byte流
            logger.info("=========>把String转化成byte流");
            bytes = s.getBytes(UTF8_charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Blob Encoding Error!");
        }
        preparedStatement.setBytes(i, bytes);

    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if(resultSet.getBytes(s) != null){
            byte[] returnValue = resultSet.getBytes(s);
            try {
                //###把byte转化成string
                logger.info("=========>把byte转化成string");
                String result = new String(returnValue, UTF8_charset);
                return result;
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Blob Encoding Error!");
            }
        }
        return null;
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if(resultSet.getBytes(i) != null) {
            byte[] returnValue = resultSet.getBytes(i);
            try {
                String result = new String(returnValue, UTF8_charset);
                return result;
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Blob Encoding Error!");
            }
        }
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
